package com.example.springboot159.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


public class HttpClientHelper {

    /**
     * send get request
     *
     * @param urlParams
     * @param params
     * @param charset
     * @return
     * @throws IOException
     */
    public static String sendGet(String urlParams, Map<String, Object> params, String charset) throws IOException {
        StringBuffer sb = new StringBuffer();
        StringBuilder stringBuilder = new StringBuilder();
        checkParam(params, stringBuilder);
        HttpURLConnection connection = null;
        BufferedReader br = null;
        URL url;
        try {
            if (stringBuilder != null && stringBuilder.length() > 0) {
                url = new URL(urlParams + "?" + stringBuilder.substring(0, stringBuilder.length() - 1));
            } else {
                url = new URL(urlParams);
            }
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

            connection.connect();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
            getContent(br, sb);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(br, connection);
        }
        return sb.toString();
    }

    /**
     * send post request
     *
     * @param urlParam
     * @param params
     * @param charset
     * @return
     * @throws Exception
     */
    public static String sendPost(String urlParam, Map<String, Object> params, String charset) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        checkParam(params, stringBuilder);
        StringBuffer sb = new StringBuffer();

        HttpURLConnection connection = null;
        OutputStreamWriter osw;
        BufferedReader br = null;

        try {
            URL url = new URL(urlParam);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (stringBuilder != null && stringBuilder.length() > 0) {
                osw = new OutputStreamWriter(connection.getOutputStream(), charset);
                osw.write(stringBuilder.substring(0, stringBuilder.length() - 1));
                osw.flush();
                //使用字节流与字符流的不同之处在于：字节流是直接与数据产生交互，而字符流在与数据交互之前要经过一个缓冲区 。
                //也就是说，字符流中的数据是暂存于缓冲区的，如果不将缓冲区中的数据真正地送达"目的地"，结果就可能会和自己想的不太一样。要清空缓冲区中的数据（即将缓冲区中数据送达目的地）有两种办法：close,flush
            }
            //将返回的数据转成StringBuffer对象.
            if (getContentLength(connection) > 0) {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
                getContent(br, sb);
            }
        } catch (IOException e) {
            throw new Exception(e);
        } finally {
            close(br, connection);
        }
        return sb.toString();
    }


    /**
     * send post request
     *
     * @param urlParam
     * @param json
     * @param charset
     * @return
     * @throws IOException
     */
    public static String sendPost(String urlParam, String json, String charset) throws IOException {
        StringBuffer sb = new StringBuffer();
        HttpURLConnection connection = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlParam);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (json != null && json.length() > 0) {
                osw = new OutputStreamWriter(connection.getOutputStream(), charset);
                osw.write(json);
                osw.flush();
            }
            //读取返回内容
            if (getContentLength(connection) > 0) {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
                getContent(br, sb);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    osw = null;
                    throw new IOException();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                        connection = null;
                    }
                }
            }
            if (br != null) {
                br.close();
            }
        }
        return sb.toString();
    }


    public static int getContentLength(HttpURLConnection connection) {
        return Integer.parseInt(connection.getHeaderField("Content-Length"));
    }


    public static StringBuilder checkParam(Map<String, Object> params, StringBuilder stringBuilder) {

        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                stringBuilder.append(entry.getKey());
                stringBuilder.append("=");
                stringBuilder.append(entry.getValue());
                stringBuilder.append("&");
            }
        }
        return stringBuilder;
    }


    public static StringBuffer getContent(BufferedReader br, StringBuffer sb) throws IOException {
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        return sb;
    }


    public static void close(BufferedReader br, HttpURLConnection connection) throws IOException {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                br = null;
                throw new IOException(e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                    connection = null;
                }
            }
        }
    }

}
